package com.zzy.furns.web;

import com.google.gson.Gson;
import com.zzy.furns.domain.Member;
import com.zzy.furns.service.MemberService;
import com.zzy.furns.service.impl.MemberServiceImpl;
import com.zzy.furns.utils.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@SuppressWarnings({"all"})
public class MemberServlet extends BasicServlet {
    private MemberService memberService = new MemberServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        Member member = memberService.login(username, password);
        if (member == null){
            //用户名或密码错误，登陆失败，返回登陆界面重新登陆
            req.setAttribute("error","用户或密码错误");
            req.setAttribute("username",username);
            req.getRequestDispatcher("/views/member/login.jsp").forward(req,resp);
            return;
        }

        //登陆成功
        HttpSession session = req.getSession();
        session.setAttribute("member",member);
        req.getRequestDispatcher("/views/member/login_ok.jsp").forward(req,resp);
    }

    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");

        //注册失败后的数据回显
        req.setAttribute("registerMemberMsg",new Member(null, username, password, email));

        //校验验证码信息与有效性
        if (!DataUtils.checkCode(req)){
            //校验失败
            req.getRequestDispatcher("/views/member/login.jsp").forward(req,resp);
            return;
        }

        if (memberService.isExistsUsername(username)){
            //用户名已存在，返回注册页面重新注册
            req.setAttribute("registerErrorMsg", "用户名已存在");
            req.getRequestDispatcher("/views/member/login.jsp").forward(req,resp);
            return;
        }

        //用户名不存在
        if (!memberService.registerMember(new Member(null,username,password,email))){
            //注册失败
            req.setAttribute("registerErrorMsg", "数据库写入失败");
            req.getRequestDispatcher("/views/member/register_fail.html").forward(req,resp);
            return;
        }

        //注册成功
        req.getRequestDispatcher("/views/member/register_ok.html").forward(req,resp);
    }

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         *  req.getSession() 得到一个与当前浏览器相关联的Session对象
         */
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath());
    }

    /**
     * 检验注册名是否存在
     */
    protected void isExistName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        Gson gson = new Gson();

        String json = null;

        if (memberService.isExistsUsername(username)){
            //用户名已存在
            json = gson.toJson("会员名已存在");
        } else {
            json = gson.toJson("会员名不存在");
        }

        writer.write(json);
        writer.flush();
        writer.close();
    }

    /**
     * 使用Ajax验证验证码的有效性（当作练习玩玩） 正好回忆下验证码流程
     */
    protected void checkCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //前端提交的验证码
        String code = req.getParameter("code");

        //系统生成的验证码
        String orginCode = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);

        Gson gson = new Gson();
        Map<String, Boolean> map = new HashMap<>();

        if (orginCode.equals(code)){
            //验证通过
            map.put("checkResult",true);
        } else {
            //验证失败
            map.put("checkResult",false);
        }

        String json = gson.toJson(map);

        PrintWriter writer = resp.getWriter();
        writer.write(json);
        writer.flush();
        writer.close();
    }
}
